package com.wish.contract.controller;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wish.common.core.domain.R;
import com.wish.common.core.usconfig.common.MsgResult;
import com.wish.common.core.utils.StringUtils;
import com.wish.common.core.utils.bean.BeanUtils;
import com.wish.common.core.web.domain.AjaxResult;
import com.wish.common.security.utils.SecurityUtils;
import com.wish.contract.entity.*;
import com.wish.contract.entity.vo.ContractVO;
import com.wish.contract.entity.vo.HouseInfoVO;
import com.wish.contract.service.*;
import com.wish.system.api.RemoteFileService;
import com.wish.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 高露雯-收房合同表  曹佳林 前端控制器
 * </p>
 *
 * @author cjl
 * @since 2022-03-26
 */
@RestController
@RequestMapping("/charge")
public class TSfContractController {

    @Autowired
    private ITSfContractService contractService;
    @Autowired
    private ITbHouseInfoService houseInfoService;
    @Autowired
    private ISysRegionService regionService;
    @Autowired
    private ITMBankService bankService;
    @Autowired
    private ITMOwnerService ownerService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ITCwPaymentPlanService paymentPlanService;
    @Autowired
    private ITMAttachmentService attachmentService;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private RemoteFileService remoteFileService;

    @GetMapping("/getToken")
    public MsgResult getToken() {
        String uuid = IdUtil.fastUUID();
        redisTemplate.opsForValue().set(uuid, 1, 1, TimeUnit.HOURS);
        return MsgResult.succeed(uuid);
    }

    /**
     * 查询房产信息
     */
    @GetMapping("/houseInfoPage")
    public MsgResult houseInfoPage(HouseInfoVO houseInfoVO) {
        return MsgResult.succeed(houseInfoService.houseInfoPage(houseInfoVO));
    }

    /**
     * 开户行所在省列表
     */
    @GetMapping("/getBankAccountProvinceList")
    public MsgResult getBankAccountProvinceList() {
        QueryWrapper<SysRegion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 1);
        return MsgResult.succeed(regionService.list(queryWrapper));
    }

    /**
     * 获取总行列表
     */
    @GetMapping("/getBankIdOptionList")
    public MsgResult getBankIdOptionList() {
        return MsgResult.succeed(bankService.list());
    }

    /**
     * 修改租约时间
     */
    @PostMapping("/getChangeDuring")
    public MsgResult getChangeDuring(@RequestBody TSfContract tSfContract) {
        Date leaseStartTime = tSfContract.getLeaseStartTime();
        if (leaseStartTime == null) {
            tSfContract.setLeaseStartTime(new Date());
        }
        DateTime dateTime = DateUtil.offset(tSfContract.getLeaseStartTime(), DateField.YEAR, tSfContract.getReserve2());
        tSfContract.setLeaseEndTime(DateUtil.offsetDay(dateTime, -1));
        return MsgResult.succeed(tSfContract);
    }

    /**
     * 收房付款单
     */
    @PostMapping("/getPaymentPlanList")
    public MsgResult getPaymentPlanList(@RequestBody ContractVO contractVO) {
        return MsgResult.succeed(paymentPlanService.getPaymentPlans(contractVO));
    }

  /*  //计算付款账单
    private List<TCwPaymentPlan> gettCwPaymentPlans(ContractVO contractVO) {
        //付款单集合

        List<TCwPaymentPlan> tCwPaymentPlans = new ArrayList<TCwPaymentPlan>();

        //房产押金
        BigDecimal depositMoney = contractVO.getDepositMoney();
        //押几
        Integer depositType = contractVO.getDepositType();
        //总押金
        BigDecimal multiply = depositMoney.multiply(new BigDecimal(depositType));

        //月租金
        BigDecimal monthRent = contractVO.getMonthRent();
        //付几
        Integer paymentType = contractVO.getPaymentType();
        //租金
        BigDecimal multiply1 = monthRent.multiply(new BigDecimal(paymentType));

        Date leaseStartTime = contractVO.getLeaseStartTime();
        //押金账单
        if (!multiply.equals(BigDecimal.ZERO)) {
            TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
            tCwPaymentPlan.setContractType(1);
            tCwPaymentPlan.setPayType(1);
            tCwPaymentPlan.setPayState(1);
            tCwPaymentPlan.setBillType(3);
            tCwPaymentPlan.setPaymentAmount(multiply);
            //税费
            tCwPaymentPlan.setTax(new BigDecimal(0));
            //序号
            tCwPaymentPlan.setPayNumber(0);
            //开始
            tCwPaymentPlan.setPaymentDaysBegin(leaseStartTime);
            //应付日期
            tCwPaymentPlan.setPayableDate(leaseStartTime);
            tCwPaymentPlan.setPaymentDaysEnd(DateUtil.offsetDay(DateUtil.offsetMonth(leaseStartTime, 1), -1));
            tCwPaymentPlan.setCreateUserid(SecurityUtils.getUserId());
            tCwPaymentPlans.add(tCwPaymentPlan);
        }


        //租金账单
        for (int i = 1; ; i++) {
            TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
            tCwPaymentPlan.setContractType(1);
            tCwPaymentPlan.setPayType(1);
            //付款状态
            tCwPaymentPlan.setPayState(1);
            tCwPaymentPlan.setBillType(3);
            //序号
            tCwPaymentPlan.setPayNumber(i);
            //税费
            tCwPaymentPlan.setTax(new BigDecimal(0));
            tCwPaymentPlan.setPaymentDaysBegin(leaseStartTime);
            //应付日期
            tCwPaymentPlan.setPayableDate(leaseStartTime);
            //开始日期变化
            leaseStartTime = DateUtil.offsetMonth(leaseStartTime, paymentType);
            DateTime dateTime = DateUtil.offsetDay(leaseStartTime, -1);
            tCwPaymentPlan.setCreateUserid(SecurityUtils.getUserId());
            //最后一期结束日期>=总结束日期, 结束循环
            if (DateUtil.compare(dateTime, contractVO.getLeaseEndTime()) >= 0) {
                //获取月份差值(不足一个月不计算)
                double floor = Math.floor((DateUtil.dayOfYear(dateTime) - DateUtil.dayOfYear(contractVO.getLeaseEndTime())) / 30.0);
                tCwPaymentPlan.setPaymentAmount(monthRent.multiply(new BigDecimal(paymentType - floor)));
                tCwPaymentPlan.setPaymentDaysEnd(contractVO.getLeaseEndTime());
                tCwPaymentPlans.add(tCwPaymentPlan);
                break;
            }
            tCwPaymentPlan.setPaymentAmount(multiply1);
            tCwPaymentPlan.setPaymentDaysEnd(dateTime);
            tCwPaymentPlans.add(tCwPaymentPlan);
        }
        return tCwPaymentPlans;
    }
*/
    /**
     * 保存合同
     */
    @Transactional //开启事务
    @PostMapping("/saveContract")
    public MsgResult saveContract(@RequestBody ContractVO contractVO) {
        System.out.println(contractVO);
        String token = contractVO.getReserve3();
        Boolean delete = redisTemplate.delete(token);
//        if(!delete){
//            return MsgResult.fail(500,"生成合同过期, 或合同已保存",null);
//        }

        //如果上一合同编号未空则为原合同, 如果不为空则为续约合同
        Long lastContractId = contractVO.getLastContractId();
        boolean last = lastContractId == null;
        //若为续约合同则变更原合同为已续约
        if(!last){
            contractService.updateXyStatus(lastContractId);
        }

        //使用hutool工具类IdUtil.getSnowflake获取Snowflake全局单例对象。
        Snowflake snowflake = IdUtil.getSnowflake();
        //雪花算法生成合同id
        contractVO.setSfContractNo("SFHT" + snowflake.nextId());

        Boolean signWithOwner = contractVO.getSignWithOwner();
        TMOwner tmOwner = new TMOwner();
        BeanUtils.copyBeanProp(tmOwner, contractVO);

        if (StringUtils.isNotEmpty(contractVO.getOwnerContactAddress()))
            contractVO.setAddress(contractVO.getOwnerContactAddress());
        if(StringUtils.isNotEmpty(tmOwner.getIdCard()))
            contractVO.setOwnerIdCard(tmOwner.getIdCard());
        if(StringUtils.isNotEmpty(tmOwner.getMobile()))
            contractVO.setOwnerMobile(tmOwner.getMobile());
        if(StringUtils.isNotEmpty(tmOwner.getAddress()))
            contractVO.setOwnerContactAddress(tmOwner.getAddress());
        if(StringUtils.isNotEmpty(tmOwner.getUrgMobile()))
            contractVO.setSignUserEmergencyPhone(tmOwner.getUrgMobile());


        //如果业主为签约人, 将业主信息放入签约人
        if (!signWithOwner) {
            contractVO.setSignUserName(contractVO.getOwnerName());
            contractVO.setSignUserIdCard(contractVO.getOwnerIdCard());
            contractVO.setSignUserMobile(contractVO.getOwnerMobile());
        }
        Long userId = SecurityUtils.getUserId();
        tmOwner.setCreateUserid(userId);
        tmOwner.setCreateTime(new Date());
        //如果为原合同添加业主
        if(last){

            ownerService.save(tmOwner);
            //将业主id存入合同
            contractVO.setOwnerId(tmOwner.getId());
        }
        //合同签订时间，（暂定设置为提交日期）
        contractVO.setConSignTime(new Date());
        //合同录入时间，（暂定设置为提交日期）
        contractVO.setConInfoTime(new Date());
        //合同审核时间，（暂定设置为提交日期）
        contractVO.setConAudTime(new Date());
        contractVO.setCreateTime(new Date());
        //创建用户id
        contractVO.setCreateUserid(userId);
        contractVO.setOperId(userId);
        contractVO.setSfUserId(userId);
        String username = SecurityUtils.getUsername();
        contractVO.setSignUserName(username);
        contractVO.setSfUserName(username);
        contractVO.setStatus(2);
        //保存合同
        contractService.save(contractVO);
        Long contractVOId = contractVO.getId();
        String sfContractNo = contractVO.getSfContractNo();

        //保存附件
        List<TMAttachment> attachments = contractVO.getAttachments();
        if (attachments != null && attachments.size() > 0){
            for (TMAttachment attachment : attachments) {
                //图片对象保存合同编号
                attachment.setRelationId(contractVO.getId());
                attachment.setCreateUserid(userId);
                //类型收房合同
                attachment.setRelationType(10);
                attachment.setCreateTime(new Date());
            }
            attachmentService.saveBatch(attachments);
        }


        //保存付款单
        //后端重新再次计算账单
        List<TCwPaymentPlan> paymentPlans = paymentPlanService.getPaymentPlans(contractVO);
        for (TCwPaymentPlan paymentPlan : paymentPlans) {
            //付款单号
            paymentPlan.setPayOrderNo("SFHT" + snowflake.nextId());
            paymentPlan.setContractId(contractVOId);
            paymentPlan.setContractNo(sfContractNo);
            paymentPlan.setCreateTime(new Date());
            paymentPlan.setCreateUserid(userId);
            paymentPlan.setOwnerName(contractVO.getOwnerName());

        }
        paymentPlanService.saveBatch(paymentPlans);

        return MsgResult.succeed();
    }

    /**
     * 图片上传
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传图片异常，请联系管理员");
        }
        R<SysFile> fileResult = remoteFileService.upload(file);
        if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
            return AjaxResult.error("文件服务异常，请联系管理员");
        }
        String url = fileResult.getData().getUrl();

        AjaxResult ajax = AjaxResult.success();
        ajax.put("imgUrl", url);
        return ajax;

    }

    /**
     * 续约查询合同列表
     * 合同状态 status=2已提交
     * 续约状态 xy_status=0 未续约
     * 逻辑删除 del_flg=0 未删除
     */
    @GetMapping("/contractPage")
    public MsgResult contractPage(ContractVO contractVO){
        //分页
        IPage<TSfContract> page = new Page<TSfContract>(contractVO.getCurrent(),contractVO.getSize());
        QueryWrapper<TSfContract> queryWrapper = new QueryWrapper<>();
        //合同状态 status=2已提交
        queryWrapper.eq("status",2);
        //续约状态 xy_status=0 未续约
        queryWrapper.eq("xy_status",0);
        //逻辑删除 del_flg=0 未删除
        queryWrapper.eq("del_flg",0);
        //业主名称模糊查询
        String ownerName = contractVO.getOwnerName();
        if(StringUtils.isNotEmpty(ownerName))
            queryWrapper.like("owner_name",ownerName);
        // 小区名称模糊查询
        String premiseName = contractVO.getPremiseName();
        if(StringUtils.isNotEmpty(premiseName))
            queryWrapper.like("premise_name",premiseName);
        //分页查询
        IPage<TSfContract> contractIPage = contractService.page(page, queryWrapper);
        return MsgResult.succeed(contractIPage);
    }

//    public static void main(String[] args) {
//        int compare = DateUtil.compare(new Date(), DateUtil.offsetDay(new Date(), -1));
//        System.out.println(compare);
//    }
}
